package com.example.skyline.service;

import com.example.skyline.entity.User;
import com.example.skyline.exception.ServiceException;
import com.example.skyline.mapper.VerificationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationService {

    private static final String CHARACTERS = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // 登录验证码字符集‘
    private static final int CODE_LENGTH = 6; // 登录验证码长度
    private static final SecureRandom RANDOM = new SecureRandom();

    @Autowired
    private VerificationMapper verificationMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Transactional
    public String createVerificationCode(String phoneNumber) {
        // 账号是否存在
        User dbUser = verificationMapper.selectByUsername(phoneNumber);
        // 账号不存在，则向传递报错信息信息
        if (dbUser == null) {
            throw new ServiceException("500","账号不存在,无法获取验证码"); // 账号不存在，则向传递报错信息信息 下面代码就不会执行了
        }

        // 存在生成 登录 验证码
        StringBuilder verityCode = new StringBuilder(6);
        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length());
            verityCode.append(CHARACTERS.charAt(index));
        }

        BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(phoneNumber);
        boundValueOperations.set(verityCode.toString(), 90, TimeUnit.SECONDS);

        return verityCode.toString();
    }

}
